﻿using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetProductionReportCommandHanders : IRequestHandler<GetProductionReportCommands, APIPaging<List<ProductionReport>>>
    {
        private readonly IBaseRepository<ProductionReport> _repository;

        public GetProductionReportCommandHanders(IBaseRepository<ProductionReport> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 显示生产报工
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<ProductionReport>>> Handle(GetProductionReportCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<ProductionReport>> result =new APIPaging<List<ProductionReport>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            var sql = "select * from ProductionReport where IsDelete=false ORDER BY ProductionReportId DESC";
            var list = await _repository.SelectAsync(sql);
            if (!string.IsNullOrEmpty(request.ProductionId))
            {
                list = list.Where(x => x.ProductionId.Contains(request.ProductionId)).ToList();
            }
            if(!string.IsNullOrEmpty(request.ProductMaterialName))
            {
                list = list.Where(x => x.ProductMaterialName.Contains(request.ProductMaterialName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductMaterialCode))
            {
                list = list.Where(x => x.ProductMaterialCode.Contains(request.ProductMaterialCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.Caller))
            {
                list = list.Where(x => x.Caller.Contains(request.Caller)).ToList();
            }
            if (request.ReportTypeId>0)
            {
                list=list.Where(x=>x.ReportTypeId== request.ReportTypeId).ToList();
            }
            if (request.Status > 0)
            {
                list = list.Where(x => x.Status == request.Status).ToList();
            }
            result.TotalCount = list.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            list=list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data= list;
            return result;
        }
    }
}
